<template>
  <div class="conversation-page">
    <SideBarComponent
      @new-conversation="createNewConversation"
      @switch-conversation="switchConversation"
      @clear-all-conversations="clearAllConversations"
    />
    <MessageContainer
      :messages="messages"
      :loading="loading"
      @message-sent="handleMessage"
      @file-upload="handleUpload"
      :uploadfiles="uploadfiles"
      @closemodel="handleCancel"
      ref="mainContent"
    />
  </div>
</template>

<script>
import SideBarComponent from "../components/SideBarComponent.vue";
import MessageContainer from "../components/MessageContainer.vue";
import axios from "axios";

export default {
  name: "ConversationPage",

  components: {
    SideBarComponent,
    MessageContainer,
  },

  data() {
    return {
      messages: [],
      allConversations: [],
      loading: false,
      uploadfiles: false,
    };
  },

  methods: {
    handleMessage(newMsg) {
      this.messages.push({ text: newMsg, isUser: true });
      this.$nextTick(() => {
        this.scrollToBottom();
        this.autoReply(newMsg);
      });
    },

    handleUpload() {
      this.uploadfiles = true;
    },

    handleCancel() {
      this.uploadfiles = false;
    },

    autoReply(userMessage) {
      this.loading = true;
      const headers = {
        "Content-Type": "application/json",
      };

      const data = {
        query: userMessage,
        max_memory: "3",
        uid: this.$refs.mainContent.randomId, // 使用 this.$refs.messageContainer.randomId
      };

      axios
        .post("/api/web/conversation", data, { headers })
        .then((response) => {
          console.log("API Response:", response.data); // 添加日志输出
          const { sql, chart, desc, table } = response.data;
          this.messages.push({
            text: desc || "不好意思，出了一点问题，请稍后再试。",
            chart: chart || null,
            table: table || null,
            sql: sql || null,
            isUser: false,
            isSql: false,
          });
          console.log("Chart data before nextTick:", chart); // 添加日志输出

          this.$nextTick(() => {
            this.scrollToBottom();
          });
          console.log("Chart data:", chart); // 添加日志输出
        })
        .catch((error) => {
          console.error("API Error:", error); // 添加日志输出
          const errorMessage = "抱歉，出了一点问题，请稍后再试。";
          this.messages.push({ text: errorMessage, isUser: false });
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },

    scrollToBottom() {
      console.log("this.message输出：", this.messages);
      this.$refs.mainContent.scrollToBottom();
    },

    createNewConversation() {
      const newConversation = {
        title: `对话 ${this.allConversations.length + 1}`,
        messages: [...this.messages],
      };
      this.allConversations.push(newConversation);
      this.messages = [
        {
          text: `<h3 style="margin-top: 0; margin-bottom: 10px; font-size: 23px; line-height: 1.4;">
  你好，<br>我是知数ChatBI
</h3>
<span style="color: #494949; display: block; margin-bottom: 10px;">
  我是你的智能数据分析助手，能帮你快速分析数据，并解答你的各种问题。
</span>
<span style="color: #494949; display: block; margin-bottom: 5px;">
  你可以试着这样问我：
</span>
<span style="color: #494949; display: block; background-color: #f0f0f0; padding: 10px; border-radius: 5px; margin-top: 10px;">
  帮我分析一下我上传的Excel表
</span>
<span style="color: #494949; display: block; background-color: #f0f0f0; padding: 10px; border-radius: 5px; margin-top: 10px;">
  分析最近两个月以来销量的趋势，并预测未来的销量。
</span>
              `,
          isUser: false,
        },
      ];
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    switchConversation(conversation) {
      this.messages = conversation.messages;
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    clearAllConversations() {
      this.allConversations = [];
    },
  },

  mounted() {
    const welcomeMessage = `<h3 style="margin-top: 0; margin-bottom: 10px; font-size: 23px; line-height: 1.4;">
  你好，<br>我是知数ChatBI
</h3>
<span style="color: #494949; display: block; margin-bottom: 10px;">
  我是你的智能数据分析助手，能帮你快速分析数据，并解答你的各种问题。
</span>
<span style="color: #494949; display: block; margin-bottom: 5px;">
  你可以试着这样问我：
</span>
<span style="color: #494949; display: block; background-color: #f0f0f0; padding: 10px; border-radius: 5px; margin-top: 10px;">
  帮我分析一下我上传的Excel表
</span>
<span style="color: #494949; display: block; background-color: #f0f0f0; padding: 10px; border-radius: 5px; margin-top: 10px;">
  分析最近两个月以来销量的趋势，并预测未来的销量。
</span>
              `;
    this.messages.push({ text: welcomeMessage, isUser: false });
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
};
</script>

<style>
.conversation-page {
  display: flex;
  height: 100%;
  width: calc(100% - 260px);
  margin-left: 250px;
  margin-top: 67px;

  overflow-x: hidden; /* 添加这一行 */
}
</style>
